package com.junhong.forum.batch;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringBufferInputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.ext.DefaultHandler2;

import com.junhong.util.StringUtil;

public class XmlProcessor {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

	/**
	 * parse the store's sourcexml links in the format <links><link>url</link></links>
	 * 
	 * @param content
	 * @return
	 */
	public static List<String> parse(String content) {
		try {
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser saxParser = factory.newSAXParser();
			final List<String> xmlSourceLinks = new ArrayList<String>();
			DefaultHandler2 handler = new DefaultHandler2() {
				boolean	link	= false;

				public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
					if (qName.equalsIgnoreCase("link")) {
						link = true;
					}

				}

				public void characters(char ch[], int start, int length) throws SAXException {
					if (link) {
						xmlSourceLinks.add(new String(ch, start, length));
						link = false;
					}
				}

				public void startCDATA() {
					link = true;
				}

			};

			InputStream inputStream = new StringBufferInputStream(content);
			Reader reader = new InputStreamReader(inputStream, "UTF-8");
			InputSource is = new InputSource(reader);
			is.setEncoding("UTF-8");
			saxParser.parse(is, handler);
			return xmlSourceLinks;
		} catch (Exception e) {
			System.out.println("the following exception happened while parsing: " + content);
			e.printStackTrace();

		}
		return new ArrayList<String>();

	}

	public static String parseXmlByTagName(String xml, String tagName) {
		String result = "0";
		if (StringUtil.isNullOrBlank(xml)) {
			return result;
		}
		XMLInputFactory factory = XMLInputFactory.newInstance();
		XMLStreamReader reader = null;
		try {
			reader = factory.createXMLStreamReader(new StringBufferInputStream(xml));
			boolean foundTotalPages = false;
			main: while (reader.hasNext()) {
				int event = reader.next();
				switch (event) {
				case XMLStreamConstants.START_ELEMENT:
					if (reader.getLocalName().equalsIgnoreCase(tagName)) {
						foundTotalPages = true;
						break;
					}
				case XMLStreamConstants.CHARACTERS:
					if (foundTotalPages) {
						result = reader.getText().trim();
						break main;
					}
				}
			}
		} catch (XMLStreamException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (Exception ex) {
					System.out.println("Not able to close XMLStreamReader, potential Memory Leak");
					ex.printStackTrace();
				}
			}
		}

		return result;

	}

	public static String parseXmlByTagName(InputStream xml, String tagName) {
		String result = "0";
		XMLInputFactory factory = XMLInputFactory.newInstance();
		try {
			XMLStreamReader reader = factory.createXMLStreamReader(new BufferedInputStream(xml));
			boolean foundTotalPages = false;
			main: while (reader.hasNext()) {
				int event = reader.next();
				switch (event) {
				case XMLStreamConstants.START_ELEMENT:
					if (reader.getLocalName().equalsIgnoreCase(tagName)) {
						foundTotalPages = true;
						break;
					}
				case XMLStreamConstants.CHARACTERS:
					if (foundTotalPages) {
						result = reader.getText().trim();
						break main;
					}
				}
			}
		} catch (XMLStreamException e) {
			// TODO Auto-generated catch block

			e.printStackTrace();
		}

		return result;

	}

	public static String parseXmlByTagAttribute(String xml, String tagName, String attributeName) {
		String result = "0";
		if (StringUtil.isNullOrBlank(xml)) {
			return result;
		}
		XMLInputFactory factory = XMLInputFactory.newInstance();
		XMLStreamReader reader = null;
		try {
			reader = factory.createXMLStreamReader(new StringBufferInputStream(xml));
			boolean foundTagName = false;
			main: while (reader.hasNext()) {
				int event = reader.next();
				switch (event) {
				case XMLStreamConstants.START_ELEMENT:
					if (reader.getLocalName().equalsIgnoreCase(tagName)) {
						foundTagName = true;
						result = reader.getAttributeValue(null, attributeName);
						break main;
					}
				}
			}
		} catch (XMLStreamException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (Exception ex) {
					System.out.println("Not able to close XMLStreamReader, potential Memory Leak");
					ex.printStackTrace();
				}
			}
		}

		return result;

	}
}
